package com.gxxy.spring.kp03_aop.cls02_aop.s02_annotation;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

// AOP: Aspect Oriented Programming
// aspectj: Aspect Java
// Execution表达式: 过滤method

@Aspect
// <aop:aspect ref="txMgr">
@Component
// IoC
public class TransactionManager {

	//<aop:pointcut expression="execution(* com.gxxy.spring.kp03_aop.cls02_aop.s01_xml.*Service.*(..))" id="stuService"/>
	@Pointcut("execution(* com.gxxy.spring.kp03_aop.cls02_aop.s02_annotation.*Service.*(..))")
	public void stuService() { // 方法的名称就是上面execution表达式的别名
	}

	/**
	 * 事务的开启
	 */
	//@Before("execution(* com.gxxy.spring.kp03_aop.cls02_aop.s02_annotation.*Service.*(..))")
	@Before("stuService()") // <aop:before method="begin" pointcut-ref="stuService" />
	public void begin() {
		System.out.println("TransactionManager.begin()");
	}

	/**
	 * 事务的提交
	 */
	@AfterReturning("stuService()")
	public void commit() {
		System.out.println("TransactionManager.commit()");
	}

	/**
	 * 事务的回滚
	 */
	@AfterThrowing(value="stuService()", throwing="e")
	public void rollback(Throwable e) {
		System.out.println("TransactionManager.rollback()");
		System.out.println("e: " + e.getMessage());
	}

	/**
	 * 执行完毕
	 */
	@After("stuService()")
	public void finished() {
		System.out.println("TransactionManager.finished()");
	}
	
	/**
	 * 全部, 这个方法中必须要有一个参数,这个参数能够让整个执行过程连贯起来
	 * @param point
	 */
	//@Around("stuService()")
	public void all(ProceedingJoinPoint point) {
		try {
			begin();
			point.proceed(); // 继续往下执行
			commit();
		} catch (Throwable e) {
			rollback(e);
		} finally {
			finished();
		}
	}

}
